/**
 * 封装常用方法
 * 
 * 常用正则
 * 1.手机号: const phoneReg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/
   2.身份证: const sfzReg = /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
   3.邮箱:const emailReg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/
   4.URL校验:const urlReg = /^((https?|ftp|file):\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/
   5.IPv4校验:const ipv4Reg = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/
   6.16进制颜色校验:const color16Reg = /^#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$/
   7.日期YYYY-MM-DD:const dateReg = /^\d{4}(\-)\d{1,2}\1\d{1,2}$/
   8.日期YYYY-MM-DD hh:mm:ss: const dateReg = /^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/
   9.整数:const intReg = /^[-+]?\d*$/
   10.小数:const floatReg = /^[-\+]?\d+(\.\d+)?$/
   11.保留n位小数:new RegExp(`^([1-9]+[\d]*(.[0-9]{1,${n}})?)$`)
   12.邮政编号:const postalNoReg = /^\d{6}$/
   13.QQ号:const qqReg = /^[1-9][0-9]{4,10}$/
   14.微信号:const wxReg = /^[a-zA-Z]([-_a-zA-Z0-9]{5,19})+$/
   15.车牌号:const carNoReg = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$/
   16.只含字母的字符串:const letterReg = /^[a-zA-Z]+$/
   17.包含中文的字符串:const cnReg = /[\u4E00-\u9FA5]/
   18.密码强度:const passwordReg = /(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[^a-zA-Z0-9]).{8,30}/
   19.字符串长度 n 的校验:new RegExp(`^.{${n}}$`)
   20.文件拓展名的校验:function checkFileName (arr) {
                       arr = arr.map(name => `.${name}`).join('|')
                       return new RegExp(`(${arr})$`)
                       }
                       checkFileName(['jpg', 'png', 'txt'])
   21.匹配img和src:const imgReg = /<img.*?src=[\"|\']?(.*?)[\"|\']?\s.*?>/ig

 */
import state from '@/store/index'
import {
    Toast
} from "vant";

import {
    device
} from "@/api/index"
import mobileDetect from "mobile-detect"; //具体哪个页面用到单独引用
// import Cookies from "js-cookie";
import FingerprintJS from '@fingerprintjs/fingerprintjs';


/**
 * 校验身份证格式
 * @param {number} number 
 * @returns {Boolean}
 */
export function checkIdNumber(number) {
    // return /^[1-9]\d{5}(19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/.test(number)
    return /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/.test(number)
}

/**
 * 校验手机号格式
 * @param {number} number 
 * @returns  {Boolean}
 */
export function checkMobile(number) {
    return /^1[3-9]\d{9}$/.test(number)
}

/**
 * 判断url是否是http或https 
 * @param {string} path
 * @returns {Boolean}
 */
export function isHttp(url) {
    return url.indexOf('http://') !== -1 || url.indexOf('https://') !== -1
}

/**
 * 判断有效url
 * @param {string} url
 * @returns {Boolean}
 */
export function validURL(url) {
    const reg = /^(https?|ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/
    return reg.test(url)
}

/**
 * @param {string} str
 * @returns {Boolean}
 */
export function validLowerCase(str) {
    const reg = /^[a-z]+$/
    return reg.test(str)
}

/**
 * @param {string} str
 * @returns {Boolean}
 */
export function validUpperCase(str) {
    const reg = /^[A-Z]+$/
    return reg.test(str)
}

/**
 * @param {string} str
 * @returns {Boolean}
 */
export function validAlphabets(str) {
    const reg = /^[A-Za-z]+$/
    return reg.test(str)
}

/**
 * @param {string} email
 * @returns {Boolean}
 */
export function validEmail(email) {
    const reg = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
    return reg.test(email)
}

/**
 * @param {string} str
 * @returns {Boolean}
 */
export function isString(str) {
    if (typeof str === 'string' || str instanceof String) {
        return true
    }
    return false
}

/**
 * @param {Array} arg
 * @returns {Boolean}
 */
export function isArray(arg) {
    if (typeof Array.isArray === 'undefined') {
        return Object.prototype.toString.call(arg) === '[object Array]'
    }
    return Array.isArray(arg)
}



// 日期格式化
export function parseTime(time, pattern) {
    if (arguments.length === 0 || !time) {
        return null
    }
    const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
    let date
    if (typeof time === 'object') {
        date = time
    } else {
        if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
            time = parseInt(time)
        } else if (typeof time === 'string') {
            time = time.replace(new RegExp(/-/gm), '/').replace('T', ' ').replace(new RegExp(/\.[\d]{3}/gm), '');
        }
        if ((typeof time === 'number') && (time.toString().length === 10)) {
            time = time * 1000
        }
        date = new Date(time)
    }
    const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
    }
    const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
        let value = formatObj[key]
        // Note: getDay() returns 0 on Sunday
        if (key === 'a') {
            return ['日', '一', '二', '三', '四', '五', '六'][value]
        }
        if (result.length > 0 && value < 10) {
            value = '0' + value
        }
        return value || 0
    })
    return time_str
}


/**
 * 身份证号脱敏处理
 * @param {String} str 
 * @returns 
 */
export function encryptIdNo(str) {
    if (null != str && str != undefined) {
      var pat = /(\d{4})\d*(\d{4})/;
      return str.replace(pat, '$1***********$2');
    } else {
      return "";
    }
  }

  
  /**
   * 姓名脱敏处理
   * @param {String} str 
   * @returns 
   */
  export function encryptName(str) {
    if (null != str && str != undefined) {
      if (str.length <= 3) {
        return "*" + str.substring(1, str.length);
      } else if (str.length > 3 && str.length <= 6) {
        return "**" + str.substring(2, str.length);
      } else if (str.length > 6) {
        return str.substring(0, 2) + "****" + str.substring(6, str.length)
      }
    } else {
      return "";
    }
  }




/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
    if (('' + time).length === 10) {
        time = parseInt(time) * 1000
    } else {
        time = +time
    }
    const d = new Date(time)
    const now = Date.now()

    const diff = (now - d) / 1000

    if (diff < 30) {
        return '刚刚'
    } else if (diff < 3600) {
        // less 1 hour
        return Math.ceil(diff / 60) + '分钟前'
    } else if (diff < 3600 * 24) {
        return Math.ceil(diff / 3600) + '小时前'
    } else if (diff < 3600 * 24 * 2) {
        return '1天前'
    }
    if (option) {
        return parseTime(time, option)
    } else {
        return (
            d.getMonth() +
            1 +
            '月' +
            d.getDate() +
            '日' +
            d.getHours() +
            '时' +
            d.getMinutes() +
            '分'
        )
    }
}



// 表单重置
export function resetForm(refName) {
    if (this.$refs[refName]) {
        this.$refs[refName].resetFields();
    }
}


/**
 * 构造树型结构数据
 * @param {*} data 数据源
 * @param {*} id id字段 默认 'id'
 * @param {*} parentId 父节点字段 默认 'parentId'
 * @param {*} children 孩子节点字段 默认 'children'
 */
export function handleTree(data, id, parentId, children) {
    let config = {
        id: id || 'id',
        parentId: parentId || 'parentId',
        childrenList: children || 'children'
    };

    var childrenListMap = {};
    var nodeIds = {};
    var tree = [];

    for (let d of data) {
        let parentId = d[config.parentId];
        if (childrenListMap[parentId] == null) {
            childrenListMap[parentId] = [];
        }
        nodeIds[d[config.id]] = d;
        childrenListMap[parentId].push(d);
    }

    for (let d of data) {
        let parentId = d[config.parentId];
        if (nodeIds[parentId] == null) {
            tree.push(d);
        }
    }

    for (let t of tree) {
        adaptToChildrenList(t);
    }

    function adaptToChildrenList(o) {
        if (childrenListMap[o[config.id]] !== null) {
            o[config.childrenList] = childrenListMap[o[config.id]];
        }
        if (o[config.childrenList]) {
            for (let c of o[config.childrenList]) {
                adaptToChildrenList(c);
            }
        }
    }
    return tree;
}


/*判断客户端*/
export function judgeClient() {
    let u = navigator.userAgent;
    let isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //判断是否是 android终端
    let isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //判断是否是 iOS终端
    // console.log('是否是Android：' + isAndroid); //true,false
    // console.log('是否是iOS：' + isIOS);
    if (isAndroid) {
        return 'android';
    } else if (isIOS) {
        return 'ios';
    } else {
        return 'h5';
    }
}

export async function getImei() {
    let imei = ''
    async function generateUniqueId() {
        const fp = await FingerprintJS.load();
        const result = await fp.get();
        return result.visitorId;
    }

    await generateUniqueId().then((uniqueId) => {
        // alert(uniqueId)
        imei = uniqueId;
    });

    return imei;
}

// 如果UUID不存在则请求注册设备
export async function generateUUID() {
    await device({
        idfa: '1',
        imei: await getImei() || '1',
        app_v: process.env.VUE_APP_V,
        system_v: '',
        name: '',
        os_type: judgeClient() == 'android' ? 1 : judgeClient() == 'ios' ? 2 : 3
    }).then(res => {
        if (res.status == 120000) {
            Toast(res.msg);
            return;
        }
        state.commit('SET_DID', res.data.did);
        state.commit('SET_APP_KEY', res.data.app_key)
    })
}

//系统的版本信息及设备信息
export function getSystemInfo() {
    var userAgent = navigator.userAgent;
    var systemVersion = "";
    var deviceInfo = "";

    // 提取系统版本信息
    var osMatch = userAgent.match(/OS (\d+_\d+_\d+)/);
    if (osMatch) {
        systemVersion = osMatch[1];
    }

    // 提取设备信息
    var deviceMatch = userAgent.match(/Mobile|Tablet|Android|iPhone|iPad|iPod/);
    if (deviceMatch) {
        deviceInfo = deviceMatch[0];
    }
    alert(navigator.userAgent)
    return {
        systemVersion: systemVersion,
        deviceInfo: deviceInfo
    };
}

export function getAppname() {
    //判断数组中是否包含某字符串
    function contains(sss, needle) {
        for (i in sss) {
            if (sss[i].indexOf(needle) > 0) return i;
        }
        return -1;
    }

    var device_type = navigator.userAgent; //获取userAgent信息
    console.log(device_type);
    var md = new mobileDetect(navigator.userAgent); //初始化mobile-detect
    var os = md.os(); //获取系统
    var model = "";

    if (os == "iOS") {
        //ios系统的处理
        os = md.os() + md.version("iPhone");
        model = md.mobile();
    } else if (os == "AndroidOS") {
        //Android系统的处理
        os = md.os() + md.version("Android");
        var sss = device_type.split(";");
        var i = contains(sss, "Build/");
        if (i > -1) {
            model = sss[i].substring(0, sss[i].indexOf("Build/"));
        }
    }
    let mobile_models = os + "_" + model;
    console.log('您的手机是：' + mobile_models); //打印系统版本和手机型号
    alert(mobile_models)
    return {
        os,
        model
    }
}

//随机16个字符
export function generateRandomString(length) {
    const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    let result = '';
    for (let i = 0; i < length; i++) {
        result += characters.charAt(Math.floor(Math.random() * characters.length));
    }
    return result;
}